package com.sqlloader.views.actions;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchPage;

import com.sqlloader.activator.Activator;
import com.sqlloader.views.DBAccessView;
import com.sqlloader.views.LoadDataView;
import com.sqlloader.views.SetColumnView;


public class OutputControlFileAction extends Action {
	private LoadDataView view;
	public OutputControlFileAction(String text, ImageDescriptor image,LoadDataView view) {
        super(text, image);
        this.view=view;
    }
	public void run() {
		FileDialog fd=new FileDialog(this.view.getSite().getShell(),SWT.SAVE );
		fd.setFilterExtensions(new String[]{"*.ctl"});
		fd.open();
		String filename=fd.getFilterPath()+"\\"+fd.getFileName();
		IWorkbenchPage workbenchPage = Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
		DBAccessView dbaccessview=(DBAccessView)workbenchPage.findView("com.sqlloader.views.DBAccessView");
		SetColumnView setcolumnview=(SetColumnView)workbenchPage.findView("com.sqlloader.views.SetColumnView");
		CCombo[] columncombos=setcolumnview.getColumncombos();
		Text[] ruleTexts=setcolumnview.getRuleTexts();
		if(columncombos!=null&&columncombos.length>0)
		{
		try {
			BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename),"UTF-8"));
			StringBuffer str=new StringBuffer();
			str.append("load data\n");
			str.append("infile '"+this.view.getDataFilename()+"'\n");
			str.append("into table "+dbaccessview.getTableCombo().getText()+"\n");
			str.append("fields terminated by ','\n");
			str.append("(");
			for(int i=0,s=columncombos.length;i<s;i++)
			{
				CCombo combo=columncombos[i];
				str.append(combo.getText());
				str.append(" ");
				str.append(ruleTexts[i].getText());
				if(i!=s-1)str.append(",");
			}
			str.append(")\n");
			
			bw.write(str.toString());
			
			bw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}
}
